<template>
    <div id="notice-detail">
        <el-row class="card-box">
            <el-card class="form-box">
                <el-form :label-position="labePosition" label-width="120px" size="mini">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="通知规则名称:">
                                <el-input v-model="ruleForm.ruleName" maxlength="50" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="通知类型:">
                                <el-select
                                    placeholder="请选择"
                                    style="width:100%"
                                    disabled
                                    v-model="ruleForm.noticeType"
                                    @change="changeParam('noticeType')"
                                >
                                    <el-option
                                        v-for="item in noticeTypeStorage"
                                        :key="item.dictKey"
                                        :label="item.dictKeyName"
                                        :value="item.dictKey"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="邮件发送方式:">
                                <el-select
                                    placeholder="请选择"
                                    style="width:calc(100% - 137px)"
                                    v-model="ruleForm.scheduleType"
                                    @change="changeParam('scheduleType')"
                                >
                                    <el-option label="实时发送" value="0"></el-option>
                                    <el-option label="定时发送" value="2"></el-option>
                                    <el-option label="汇总发送" value="1"></el-option>
                                </el-select>
                                <span>启用状态:</span>
                                <el-switch v-model="ruleForm.status" active-value="0" inactive-value="1" style="margin-left:4px" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="通知次数上限:">
                                <el-input-number
                                    v-model="ruleForm.limitTimes"
                                    @input.native="onInput"
                                    :disabled="['1', '2'].includes(ruleForm.scheduleType)"
                                    controls-position="right"
                                    :min="1"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="通知日期区间:">
                                <el-date-picker
                                    v-model="ruleForm.dates"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    style="width:90%"
                                    @change="handleDate"
                                    value-format="yyyyMMdd"
                                    format="yyyy-MM-dd"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item>
                                <template slot="label">
                                    <span>
                                        <el-tooltip>
                                            <div slot="content">
                                                {{ iconTooltipPojo[ruleForm.scheduleType] }}
                                                <!-- {{ ruleForm.scheduleType == '0' ? '通知时间段对应邮件的发送时间' : '汇总发送该时点近24小时的数据' }} -->
                                            </div>
                                            <i class="el-icon-question"></i>
                                        </el-tooltip>
                                        {{ labelPojo[ruleForm.scheduleType] }}
                                        <!-- {{ ruleForm.scheduleType == '0' ? '通知时间段:' : '通知时间点' }} -->
                                    </span>
                                </template>
                                <el-time-picker
                                    v-model="ruleForm.startTime"
                                    value-format="HHmmss"
                                    format="HH:mm:ss"
                                    placeholder="选择时间点"
                                    v-show="ruleForm.scheduleType == '1'"
                                >
                                </el-time-picker>
                                <el-time-picker
                                    is-range
                                    v-model="ruleForm.times"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    placeholder="选择时间范围"
                                    style="width:90%"
                                    @change="handleTime"
                                    value-format="HHmmss"
                                    format="HH:mm:ss"
                                    v-show="ruleForm.scheduleType == '0'"
                                >
                                </el-time-picker>
                                <!-- 间隔频率 -->
                                <el-select
                                    v-show="ruleForm.scheduleType == '2'"
                                    v-model="ruleForm.intervalTime"
                                    clearable
                                    size="mini"
                                    style="width:100%"
                                >
                                    <el-option
                                        v-for="(item, index) in intervalFrequencyData"
                                        :key="index"
                                        :value="item.dictKey"
                                        :label="item.dictKeyName"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="通知用户:">
                                <el-tooltip :disabled="!ruleForm.noticeUser || !ruleForm.noticeUser.length" effect="dark" placement="top-start">
                                    <ul slot="content" style="min-height: 18px; max-height: 200px; overflow: auto">
                                        <li :key="e" v-for="e in ruleForm.noticeUser">
                                            {{ e + ' ' + userStorageEnum[e] }}
                                        </li>
                                    </ul>
                                    <el-select
                                        placeholder="请选择"
                                        multiple
                                        filterable
                                        collapse-tags
                                        style="width:100%"
                                        clearable
                                        v-model="ruleForm.noticeUser"
                                    >
                                        <el-option
                                            v-for="item in computedUserStorage"
                                            :key="item.userCode"
                                            :label="item.userName + ' ' + item.userNickName"
                                            :value="item.userCode"
                                        >
                                            <span style="float: left">{{ item.userName + ' ' + item.userNickName }}</span>
                                        </el-option>
                                    </el-select>
                                </el-tooltip>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="通知岗位:">
                                <template slot="label">
                                    <span>
                                        <el-tooltip>
                                            <div slot="content">当同时选择通知用户和通知岗位时，取其并集</div>
                                            <i class="el-icon-question"></i>
                                        </el-tooltip>
                                        通知岗位:
                                    </span>
                                </template>

                                <el-tooltip :disabled="!ruleForm.notifier || !ruleForm.notifier.length" effect="dark" placement="top-start">
                                    <ul slot="content" style="min-height: 18px; max-height: 200px; overflow: auto">
                                        <li :key="e" v-for="e in ruleForm.notifier">
                                            {{ e + ' ' + roleStorageEnum[e] }}
                                        </li>
                                    </ul>

                                    <el-select
                                        placeholder="请选择"
                                        multiple
                                        filterable
                                        collapse-tags
                                        style="width:100%"
                                        clearable
                                        v-model="ruleForm.notifier"
                                    >
                                        <el-option
                                            v-for="item in computedRoleStorage"
                                            :key="item.roleCode"
                                            :label="item.roleCode + ' ' + item.roleName"
                                            :value="item.roleCode"
                                        >
                                            <span style="float: left">{{ item.roleCode + ' ' + item.roleName }}</span>
                                        </el-option>
                                    </el-select>
                                </el-tooltip>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="正文发送列设置:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    filterable
                                    collapse-tags
                                    style="width:100%"
                                    clearable
                                    v-model="ruleForm.columns"
                                    :disabled="!isEdit"
                                >
                                    <el-option v-for="item in computedColumns" :key="item.field" :label="item.title" :value="item.field"></el-option>
                                </el-select>
                                <!-- <span>启用状态:</span>
                                <el-switch v-model="ruleForm.status" active-value="0" inactive-value="1" style="margin-left:2px" /> -->
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
        </el-row>
        <el-row class="card-box">
            <el-card>
                <el-row>
                    <div style="display:inline-block">
                        <span>邮件主题： </span>
                    </div>
                    <div style="display:inline-block;width:calc(100% - 150px)">
                        <el-input v-model="ruleForm.emailSubject" :disabled="!isEdit" size="mini" style="width:100%"></el-input>
                    </div>

                    <div class="link-box">
                        <el-link icon="el-icon-edit" v-show="!isEdit" @click="isEdit = !isEdit">编辑</el-link>
                        <el-link icon="el-icon-view" v-show="isEdit" @click="isEdit = !isEdit">预览</el-link>
                    </div>
                </el-row>
                <el-row class="email-title">
                    <h2 v-show="!isEdit">{{ ruleForm.greeting }}</h2>
                    <div v-show="isEdit" class="title-ipt">
                        <el-input v-model="ruleForm.greeting"></el-input>
                    </div>
                </el-row>
                <el-row style="margin-bottom:10px">
                    <div v-show="!isEdit" class="text-box">{{ ruleForm.mainBody }}</div>
                    <el-input v-show="isEdit" type="textarea" autosize placeholder="请输入内容" v-model="ruleForm.mainBody"> </el-input>
                </el-row>
                <el-row>
                    <div style="width: 100%; height:calc(100vh - 600px); margin: 0 auto;">
                        <RiskTableP
                            ref="risk-table"
                            :tableConfig="tableConfig"
                            :tableData="emailTable"
                            :column="emailTableColumns"
                            :key="emailTableKey"
                            v-loading="tableLoading"
                            v-if="ruleForm.columns.length > 0"
                        >
                        </RiskTableP>
                    </div>
                </el-row>
            </el-card>
        </el-row>
        <el-row class="card-box">
            <el-card>
                <div class="btns">
                    <el-button @click="$emit('close-tab', data.name)">取消</el-button>
                    <el-button v-if="isShowSubmit" type="primary" @click="submit" :loading="btnLoading">确认</el-button>
                </div>
            </el-card>
        </el-row>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import RiskEntryInputs from '@/common/components/risk-entry-inputs.vue';
import { changeOptions, dateFormat, numberFormat, sortBy, timeFormat, unitShow } from '@/utils/tools';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { TableConfigVO } from '@/common/vo';

@Component({
    name: 'WarningNoticeDetailRiskDeviation',
    components: { RiskEntryInputs, RiskTableP },
})
export default class WarningNoticeDetailRiskDeviation extends Vue {
    @Prop() data: any;

    private labePosition: string = 'right';
    tableConfig: TableConfigVO = {
        rowKey: 'entryCode', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    private ruleForm = {
        scheduleType: '2',
        ruleName: '',
        noticeType: '11',
        limitTimes: undefined,
        dates: [],
        startDate: '',
        endDate: '',
        notifier: [],
        times: null,
        startTime: '',
        endTime: '',
        intervalTime: '', // 间隔频率
        noticeUser: [],
        columns: [],
        status: '0',
        emailSubject: '实时风险偏离度超出通知', // 邮件标题
        greeting: '实时风险偏离度超出通知',
        mainBody:
            '尊敬的领导：\n 您好！\n 根据智能风控工作台监控，从恒生同步过来的该条指令所触发条目的"计算结果偏离度"超出5‰的数据如下，请及时关注！',
    };

    private noticeTypeStorage: any[] = [{ dictKey: '11', dictKeyName: '实时风险偏离度' }];

    private userStorage: any[] = [];
    private userStorageEnum: any = {};
    private showType: string = 'addRD';

    private btnLoading: boolean = false;
    tableColumns: any[] = [
        {
            title: '风控指令序号',
            field: 'instructionNo',
            filterType: 'search',
            search: true,
            minWidth: '150',
        },
        {
            title: '恒生指令序号',
            field: 'dailyInstructionNo',
            search: true,
            minWidth: '150',
        },
        { title: '恒生指令批号', field: 'batchNo', filterType: 'search', minWidth: '150' },
        { title: '指令状态', field: 'instStatus', minWidth: '150' },
        { title: '条目编号', field: 'entryCode', filterType: 'search', minWidth: '150' },
        { title: '风险说明', field: 'entryName', filterType: 'search', minWidth: '150' },
        {
            title: '触警类型',
            field: 'thresholdType',
            align: 'center',
            minWidth: '150',
        },
        {
            title: '条目触发阈值',
            field: 'thresholdValue',
            align: 'right',
            minWidth: '150',
        },
        {
            title: '风控计算结果',
            field: 'calculateValue',
            align: 'right',
            minWidth: '150',
        },
        { title: '恒生计算结果', field: 'o32Value', align: 'right', minWidth: '150' },
        {
            title: '实时风险偏离度(%)',
            field: 'deviationValueShow',
            minWidth: '200',
        },
        {
            title: '条目比较方向',
            field: 'compareType',
            filterType: 'funnel',
            align: 'center',
            minWidth: '150',
        },
        {
            title: '计算逻辑',
            field: 'calLogicShow',
            align: 'center',
            minWidth: '150',
        },
        { title: '是否报错', field: 'errorValid', filterType: 'funnel', minWidth: '150' },
        { title: '报错信息', field: 'errorMessage', filterType: 'search', align: 'center', minWidth: '150' },
        { title: '产品代码', field: 'fundCode', filterType: 'search', align: 'center', minWidth: '150' },
        { title: '产品名称', field: 'fundName', filterType: 'search', align: 'center', minWidth: '150' },
        {
            title: '资产单元编号',
            field: 'assetCode',
            filterType: 'search',
            align: 'center',
            minWidth: '150',
        },
        {
            title: '资产单元名称',
            field: 'assetName',
            filterType: 'search',
            align: 'center',
            minWidth: '150',
        },
        { title: '组合编码', field: 'fundAccountCode', filterType: 'search', align: 'center', minWidth: '150' },
        { title: '组合名称', field: 'fundAccountName', filterType: 'search', align: 'center', minWidth: '150' },
        { title: '证券代码', field: 'stockCode', filterType: 'search', align: 'center', minWidth: '150' },
        { title: '证券名称', field: 'stockName', filterType: 'search', align: 'center', minWidth: '150' },
    ];

    private emailTable: any[] = [];

    private isEdit: boolean = false; // 文本是否在编辑状态

    private ThresholdType: any = DictionConstUtil.ThresholdType; // 触警类型

    private roleStorage: any[] = [];
    private roleStorageEnum: any = {};

    // 间隔频率下拉数据
    private intervalFrequencyData: any[] = [
        { dictKey: 5, dictKeyName: '5分钟' },
        { dictKey: 10, dictKeyName: '10分钟' },
        { dictKey: 20, dictKeyName: '20分钟' },
        { dictKey: 30, dictKeyName: '30分钟' },
        { dictKey: 60, dictKeyName: '1小时' },
        { dictKey: 120, dictKeyName: '2小时' },
        { dictKey: 180, dictKeyName: '3小时' },
        { dictKey: 360, dictKeyName: '6小时' },
        { dictKey: 480, dictKeyName: '8小时' },
    ];

    // 问号图标显示文字
    private iconTooltipPojo: any = {
        '0': '通知时间段对应邮件的发送时间',
        '1': '汇总发送该时点近24小时的数据',
        '2': '从当日0时开始，每间隔所设定的时间，汇总发送一次邮件',
    };

    // label标签
    private labelPojo: any = {
        '0': '通知时间段:',
        '1': '通知时间点:',
        '2': '间隔频率:',
    };

    // 邮件正文
    private mainBodyPojo: any = {
        '0': '尊敬的领导：\n 您好！\n 根据智能风控工作台监控，从恒生同步过来的该条指令所触发条目的"计算结果偏离度"超出5‰的数据如下，请及时关注！',
        '1':
            '尊敬的领导：\n 您好！\n 根据智能风控工作台监控，近24小时内，从恒生同步过来的指令所触发条目的"计算结果偏离度"超出5‰的数据如下，请及时关注！',
        '2': '尊敬的领导：\n 您好！\n 根据智能风控工作台监控，从恒生同步过来的该条指令所触发条目的"计算结果偏离度"超出5‰的数据如下，请及时关注！',
    };

    // 邮件发送列排序对象
    private columnSortPojo = {};
    emailTableKey: number = 0;

    async mounted() {
        if (this.data.type == 'addRD') {
            this.ruleForm.columns = this.tableColumns.map(item => item.field);
        }
        // 用户列表
        this.getUserList();
        // 角色列表
        this.getRoleList();
        this.getColumnSort();
        this.tableColumns.forEach(ele => {
            ele.sortNo = this.columnSortPojo[ele.field];
        });
    }

    // 正文发送列固定排序
    getColumnSort() {
        let columnField = this.tableColumns.map(ele => ele.field);
        columnField.forEach((item, index) => {
            this.columnSortPojo[item] = index;
        });
    }

    @Watch('data', { immediate: true, deep: true })
    watchData(newData) {
        if (newData) {
            console.log('newData --------detail', newData);
            if (newData.content) {
                let data = JSON.parse(JSON.stringify(newData.content));
                data.dates = [String(...(data.startDate || '')), String(...(data.endDate || ''))];
                if (data.scheduleType == '0') {
                    if (data.startTime) {
                        data.times = [data.startTime.toString(), data.endTime.toString()];
                    } else {
                        data.times = null;
                    }
                } else {
                    if (data.startTime) {
                        data.startTime = data.startTime.toString();
                    }
                }
                data.roleCodes = data.notifier || [];
                this.ruleForm = {
                    ...this.ruleForm,
                    ...data,
                };
                // this.ruleForm = data ?? this.ruleForm;
            }
            this.showType = newData.type;
        }
    }

    // 通知用户已选项前置
    get computedUserStorage() {
        let userStorage = changeOptions(this.ruleForm.noticeUser, this.userStorage, 'userCode');
        return userStorage;
    }

    // 通知岗位已选项前置
    get computedRoleStorage() {
        let roleStorage = changeOptions(this.ruleForm.notifier, this.roleStorage, 'roleCode');
        return roleStorage;
    }

    // 正文发送列已选项前置
    get computedColumns() {
        let tableColumns = changeOptions(this.ruleForm.columns, this.tableColumns, 'field');
        return tableColumns;
    }

    get emailTableColumns() {
        let columns = [];
        let elements = [];
        for (let i = 0; i < this.ruleForm.columns.length; i++) {
            const element = this.ruleForm.columns[i];
            if (this.tableColumns.length) {
                let ele = this.tableColumns.find(item => item.field === element);
                if (ele) {
                    columns.push(ele);
                    elements.push(element);
                }
            }
        }
        this.ruleForm.columns = elements;

        columns.forEach(ele => {
            this.$set(ele, 'sortNo', this.columnSortPojo[ele.field]);
        });
        columns = columns.sort(sortBy('sortNo', 'asc'));
        this.emailTableKey++;
        return columns;
    }

    // 显示"确认"按钮
    get isShowSubmit() {
        return ['addRD', 'editRD'].includes(this.showType);
    }

    private getUserList(): void {
        this.$axios.get('/userManage/user/list').then((res: any) => {
            if (res) {
                this.userStorage = res;
                res.forEach(element => {
                    this.userStorageEnum[element.userCode] = element.userNickName;
                });
            }
        });
    }

    changeParam(param: string) {
        if (param == 'noticeType') {
            this.ruleForm.greeting = this.noticeTypeStorage.find(item => item.dictKey == this.ruleForm.noticeType).dictKeyName + '通知';
            this.ruleForm.columns = this.tableColumns.map(item => item.field);
        } else if (param == 'scheduleType') {
            this.ruleForm.limitTimes = '1';
            this.ruleForm.startTime = '';
            this.ruleForm.endTime = '';
            this.ruleForm.intervalTime = null;
            this.ruleForm.mainBody = this.mainBodyPojo[this.ruleForm.scheduleType];
            if (this.ruleForm.scheduleType == '2') {
                this.ruleForm.limitTimes = undefined;
            }
        }
    }

    private getRoleList(): void {
        this.$axios.get('/role/query/all').then((res: any) => {
            if (res) {
                this.roleStorage = res;
                res.forEach(element => {
                    this.roleStorageEnum[element.roleCode] = element.roleName;
                });
            }
        });
    }

    // 处理日期
    private handleDate(val: any) {
        if (val && val.length) {
            this.ruleForm.startDate = val[0];
            this.ruleForm.endDate = val[1];
            return;
        }
        this.ruleForm.startDate = '';
        this.ruleForm.endDate = '';
    }

    // 处理时间
    private handleTime(val: any) {
        if (val && val.length) {
            this.ruleForm.startTime = val[0];
            this.ruleForm.endTime = val[1];
            return;
        }
        this.ruleForm.startTime = '';
        this.ruleForm.endTime = '';
    }

    private submit() {
        console.log(this.ruleForm, 'ruleForm----');
        if (!this.verify()) {
            return;
        }
        this.btnLoading = true;
        let urlType = {
            addRD: '/notice/monitor/rule/add',
            editRD: '/notice/monitor/rule/update',
        };
        let url = urlType[this.showType];
        this.$axios({ url, method: 'post', data: this.ruleForm })
            .then((res: any) => {
                this.yh_message_success('操作成功！');
                this.$emit('close-tab', this.data.name);
            })
            .finally(() => {
                this.btnLoading = false;
            });
    }

    private verify() {
        if (!this.ruleForm.ruleName) {
            this.yh_message_warn('"通知规则名称"不能为空！');
            return false;
        }
        if (this.ruleForm.scheduleType == '2' && !this.ruleForm.intervalTime) {
            this.yh_message_warn('"间隔频率"不能为空！');
            return false;
        }
        if (!this.ruleForm.noticeUser.length && !this.ruleForm.notifier.length) {
            this.yh_message_warn('"通知用户"和"通知岗位"不能同时为空！');
            return false;
        }
        // if (this.ruleForm.scheduleType === '1' && !this.ruleForm.startTime) {
        //     this.yh_message_warn('"通知时间点"不能同时为空！');
        //     return false;
        // }

        if (!this.ruleForm.columns.length) {
            this.yh_message_warn('"正文发送列"不能为空！');
            return false;
        }
        return true;
    }

    // 通知次数上限(整数)
    private onInput(e) {
        e.target.value = e.target.value.replace(/[^0-9]/g, '');
    }

    thresholdTypeFormat(value, unit): string {
        // 三目运算符, unit为'%'和'万元'、'万股'的由后端处理了，不由numberFormat方法处理
        return ['%', '万元', '万股'].includes(unit) ? value : numberFormat(value.replace(/[^0-9.]/gi, ''), unit) + unitShow(unit);
    }
}
</script>
<style lang="scss" scoped>
#notice-detail {
    .card-box {
        margin-bottom: 10px;
        .form-box {
            .left-label {
                /deep/ .el-form-item__label {
                    width: 80px !important;
                }
                /deep/ .el-form-item__content {
                    margin-left: 80px !important;
                }
            }
            /deep/ .el-input--mini {
                width: 90%;
            }
            /deep/ .el-form-item__label {
                color: black;
            }
            /deep/ .el-date-editor .el-range-separator {
                padding: 0 15px;
            }
        }
        /deep/ .el-input-number {
            width: 90%;
            .el-input--mini {
                width: 100% !important;
            }
        }
        .email-title {
            margin-bottom: 20px;
            h2 {
                text-align: center;
                font-size: 1.5em;
            }
            .title-ipt {
                width: 200px;
                margin: 0 auto;
                /deep/ .el-input__inner {
                    font-size: 1.5em;
                }
            }
        }
        .text-box {
            font-family: monospace;
            font-size: inherit;
            white-space: pre-wrap;
        }
        .link-box {
            display: inline-block;
            float: right;
            padding-right: 10px;
            /deep/ .el-link {
                margin: 0 5px;
            }
        }
        .btns {
            display: inline;
            float: right;
            padding-bottom: 20px;
        }

        /deep/ .el-checkbox-group {
            height: 25px;
            display: flex;
            justify-content: space-between;
            width: 95%;
            .el-checkbox {
                margin-right: 5px;

                .el-checkbox__label {
                    padding-left: 5px;
                }
            }
        }
    }
}
</style>
